<template>
  <div class="container">
    <div class="code">
      <input id="code" ref="codeInputRef" v-model="code" placeholder="[F1]:枪号/条码/自编码/名称"
             @keyup.enter="chooseCode">
    </div>
    <div class="btn-bar">
      <el-row>
        <el-button round size="small" type="primary" @click="saleStore">
          <font-awesome-icon icon="store"/>
          便利店
        </el-button>
        <!--        <el-button icon="el-icon-success" round size="small" type="success" @click="salePoints">积分兑换</el-button>-->
        <el-button v-if="showAddBtn" round size="small" type="danger" @click="testAdd">生成待结算</el-button>
        <el-button icon="el-icon-plus" round size="small" type="warning" @click="showPrePayDialog">预付款</el-button>
      </el-row>
    </div>
    <!-- 商品搜索弹窗 -->
    <el-dialog
        :title="'请选择商品，' + dataListToChoose.length + ' 个匹配项'"
        :visible.sync="chooseDialogVisible"
        append-to-body
        width="40%">
      <commodity-list :data-list="dataListToChoose" class="choose-list"></commodity-list>
      <span slot="footer" class="dialog-footer">
      <el-button @click="chooseDialogVisible = false">取 消</el-button>
    </span>
    </el-dialog>
  </div>
</template>
<script>
import {mapGetters} from 'vuex'
import {addFuelRecord, lockFuelRecord} from '@/api/user'
import {ENV} from '@/utils/common'
import CommodityList from '@/views/store/components/CommodityList.vue'

var Mousetrap = require('mousetrap')
export default {
  name: 'FunctionArea',
  components: {
    CommodityList
  },
  computed: {
    ...mapGetters([
      'toSettleList',
      'prePayList',
      'stationId',
      'operator',
      'toSettleListDialogVisible',
      'cartVisible',
      'stockList'
    ])
  },
  data () {
    return {
      showAddBtn: ENV !== 'prod',
      code: '',
      chooseDialogVisible: false,
      dataListToChoose: []
    }
  },
  mounted () {
    this.bindKeyboard()
    this.$bus.$off('selectedCommodity')
    this.$bus.$on('selectedCommodity', () => {
      setTimeout(() => {
        this.chooseDialogVisible = false
      }, 600)
    })
  },
  methods: {
    chooseCode () {
      console.log('回车事件')
      this.code = this.code.trim()
      // 1、是数字且长度小于3，判断为油枪号
      if (this.code && !isNaN(this.code) && this.code.length < 3) {
        // 油枪号
        // 判断为枪号
        this.$store.dispatch('setChosenGun', this.code)
        document.getElementById('code').blur()
        // 判断该油枪下是否有待结算记录
        var dataList = this.toSettleList.filter((item) => item.gunNo === this.code.trim())
        if (dataList.length === 1) {
          var row = dataList[0]
          lockFuelRecord({id: row.id, stationId: this.stationId, operator: this.operator}).then(res => {
            console.log(res)
            this.$store.dispatch('showCartDialog')
            this.$store.dispatch('addToCartList', row)
          }).catch(err => {
            console.log(err)
            this.$message.warning('该笔记录正在结算中！')
          })
        } else if (dataList.length > 1) {
          this.$store.dispatch('showToSettleListDialog')
        } else {
          this.$message.warning('找不到对应的记录')
          this.showPrePayDialog()
        }
      } else if (this.code) {
        // 商品编码、自编码、商品名称
        var tmpList = this.stockList.filter(item => item.barcode === this.code || item.customCode === this.code || item.commodityName.indexOf(this.code) > -1)
        if (tmpList.length === 1) {
          console.log(tmpList[0].stockStatus)
          // 判断该商品是否已下架，已下架则提示不允许售卖
          if (tmpList[0].stockStatus === 0) {
            this.$message.warning('该商品已下架，不允许销售！')
            return false
          }
          this.$store.dispatch('showCartDialog')
          this.$store.dispatch('addToCartList', tmpList[0])
          this.code = ''
          document.getElementById('code').blur()
        } else if (tmpList.length > 1) {
          this.dataListToChoose = tmpList
          this.chooseDialogVisible = true
          document.getElementById('code').blur()
        } else {
          this.$notify.warning({duration: 3000, message: '找不到该商品:' + this.code, title: '提示'})
        }
        this.$store.dispatch('setChosenGun', '')
      } else {
        this.$store.dispatch('setChosenGun', '')
      }
    },
    testAdd () {
      console.log('测试新增加油记录')
      var data = {
        stationId: this.stationId
      }
      addFuelRecord(data).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    },
    bindKeyboard () {
      console.log('bind f1 gogogog')
      Mousetrap.bind('f1', () => {
        console.log('go go go f1')
        if (this.cartVisible || this.toSettleListDialogVisible) {
          return false
        } else {
          // 焦点聚焦在油枪输入框内
          this.$nextTick(() => {
            this.$refs['codeInputRef'].focus()
            this.code = ''
          })
        }
      })
    },
    showPrePayDialog () {
      this.$store.dispatch('showPrePayDialog')
    },
    saleStore () {
      this.code = '888'
      this.chooseCode()
    },
    salePoints () {
      this.code = '999'
      this.chooseCode()
    }
  },
  watch: {
    cartVisible: function (newVal, oldVal) {
      if (!newVal) {
        setTimeout(() => {
          console.log('rebind keyboard')
          this.bindKeyboard()
        }, 300)
      }
    }
  },
  beforeDestroy () {
    this.$bus.$off('selectedCommodity')
  }
}
</script>
<style scoped>
.container {
  position: relative;
  text-align: center;
  width: 100%;
  height: 100%;
}

.btn-bar {
  position: absolute;
  bottom: 10px;
  left: 0;
  right: 0;
}

.code {
  position: absolute;
  bottom: 50px;
  left: 8%;
  right: 8%;
  height: 80px;
  box-sizing: border-box;
  border: 2px solid #07C160;
  border-radius: 10px;
}

.code input {
  height: 76px;
  border: none;
  width: 100%;
  border-radius: 10px;
  box-sizing: border-box;
  outline: none;
  font-size: 2rem;
  font-weight: bold;
  text-align: center;
}

.code input::placeholder {
  color: #ddd;
  font-size: 1.6rem;
  line-height: 76px;
  font-weight: normal;
}

.info {
  height: 50px;
}

.info .item {
  height: 50px;
  line-height: 50px;
  font-size: 1.2rem;
}

.item .amount {
  font-size: 2rem;
  color: red;
  font-weight: bold;
}

.change {
  color: orange;
  font-size: 2rem;
  font-weight: bold;
}
</style>
